# Untitled - By: wutong - 周六 7月 29 2023

import sensor, image, time

class TrackLine:

    def __init__():
        pass

    @staticmethod
    def roi_position_transform(roi, img_w, img_h):
        return [int(roi[0] * img_w), int(roi[1] * img_h), int(roi[2] * img_w), int(roi[3] * img_h)]

    @staticmethod
    def get_max_area_blob(blobs):
        tmp = None
        for b in blobs:
            if tmp == None:
                tmp = b
            else:
                if tmp.area() < b.area():
                    tmp = b
        return tmp

    @staticmethod
    def track_line(img):

        IMG_W = img.width()
        IMG_H = img.height()

        edge_alarm_roi =            roi_position_transform([0.25, 0, 0.5, 0.15],IMG_W,IMG_H)
        track_line_roi1 =           roi_position_transform([0.25, 0.85, 0.5, 0.15],IMG_W,IMG_H)
        track_line_roi2 =           roi_position_transform([0.25, 0.7, 0.5, 0.15],IMG_W,IMG_H)
        cross_detect_left_roi =     roi_position_transform([0.15, 0.5, 0.1, 0.5],IMG_W,IMG_H)
        cross_detect_right_roi =    roi_position_transform([0.75, 0.5, 0.1, 0.5],IMG_W,IMG_H)

        # img_bin = otsu_binary(img)
        img_bin = img.binary([(0,100)])
        img_bin = img_bin.mean(2)

        bx1 = get_max_area_blob(img_bin.find_blobs([(240,255)], roi=track_line_roi1, pixels_threshold=128))
        bx2 = get_max_area_blob(img_bin.find_blobs([(240,255)], roi=track_line_roi2, pixels_threshold=128))
        bx3 = get_max_area_blob(img_bin.find_blobs([(240,255)], roi=edge_alarm_roi, pixels_threshold=128))
        by1 = get_max_area_blob(img_bin.find_blobs([(240,255)], roi=cross_detect_left_roi, pixels_threshold=128))
        by2 = get_max_area_blob(img_bin.find_blobs([(240,255)], roi=cross_detect_right_roi, pixels_threshold=128))

        if (bx1):
            x1 = bx1.cx()
        else:
            x1 = -1

        if (bx2):
            x2 = bx2.cx()
        else:
            x2 = -1

        if (bx3):
            x3 = bx3.cx()
        else:
            x3 = -1

        if (by1):
            y1 = by1.cy()
        else:
            y1 = -1

        if (by2):
            y2 = by2.cy()
        else:
            y2 = -1

        img_bin.draw_rectangle(edge_alarm_roi)
        img_bin.draw_rectangle(track_line_roi1)
        img_bin.draw_rectangle(track_line_roi2)
        img_bin.draw_rectangle(cross_detect_left_roi)
        img_bin.draw_rectangle(cross_detect_right_roi)

        return [x1, x2, x3, y1, y2]
